import base64
import json
import os
import time

import pymysql


# 文件存放路径
file_path = r'C:\file_excel'


def getfile(messages):
    msg = json.loads(messages)
    comany = msg['comany_name']
    if msg['wait_task'] == '1':

        # 修改任务优先度并添加任务
        sql_text = 'update messages set task_set=\'s\' where comany_name=\'{}\';'.format(comany)
        sql_update(sql_text)

        for i in range(1000):
            time.sleep(2)
            sql_text = 'select task_set from messages where comany_name=\'{}\';'.format(comany)
            sql_len, sql_tuplet = sql_query(sql_text)
            if sql_tuplet[0][0] == '0':
                ls = os.listdir(file_path + '\\' + comany)
                if len(ls):
                    fp = file_path + '\\' + comany + '\\' + ls[0]
                    f = open(fp, 'rb')
                    base64_str = f.read()
                    # base64编码
                    b64 = base64.encodebytes(base64_str)
                    b64 = str(b64).replace('\\n', '').replace('\'', '')
                    f.close()
                    return {'status': 'success',
                            'code': '0',
                            'messages': {'file_name': ls[0], 'file_data': b64[1:]}}
                else:
                    return {'status': 'fail', 'code': '-1', 'error_message': '任务完成，但文件不存在'}
            if i > 998:
                return {'status': 'fail', 'code': '200', 'error_message': '超时'}

    elif msg['wait_task'] == '0':
        ls = os.listdir(file_path + '\\' + comany)
        if len(ls):
            fp = file_path + '\\' + comany + '\\' + ls[0]
            f = open(fp, 'rb')
            base64_str = f.read()
            # base64编码
            b64 = base64.encodebytes(base64_str)
            b64 = str(b64).replace('\\n', '').replace('\'', '')
            f.close()
            return {'status': 'success',
                    'code': '0',
                    'messages': {'file_name': ls[0], 'file_data': b64[1:]}}
        else:
            return {'status': 'fail', 'code': '-1', 'error_message': '任务完成，但文件不存在'}


def sql_query(sql_text):
    conn = pymysql.connect(host="127.0.0.1", user="root", database="individual_tax", password="753951", charset="utf8")
    cursor = conn.cursor()
    sql_len = cursor.execute(sql_text)
    sql_tuplet = []
    for i in range(sql_len):
        sql_tuplet.append(list(cursor.fetchone()))
    cursor.close()
    conn.close()
    return sql_len, sql_tuplet


def sql_update(sql_text):
    conn = pymysql.connect(host="127.0.0.1", user="root", database="individual_tax", password="753951", charset="utf8")
    cursor = conn.cursor()
    cursor.execute(sql_text)
    conn.commit()
    cursor.close()
    conn.close()


